<?php

namespace app\admin\controller;

use think\Db;
use think\Controller;
use app\common\model\ProductModel;

class ProductController extends Controller
{
    public function index()
    {
        return view();
    }

    public function page()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $item = new ProductModel();
            $result = $item->page(($post['page'] - 1) * $post['limit'], $post['limit']);
            return pagejson($result['data'], $result['count']);
        }
    }

    public function add()
    {
        if (!$this->request->isAjax()) {
            $data['item'] = null;
            return view('form', $data);
        }
        $post = $this->request->post();
        $item = new ProductModel($post);
        $result = $item->allowField(true)->save();
        if ($result > 0) {
            return zbcjson(true);
        } else {
            return zbcjson(false, '插入错误', 101);
        }
    }

    public function edit($id = 0)
    {
        if (!$this->request->isAjax()) {
            $data['item'] = ProductModel::get($id)->toArray();
            return view('form', $data);
        }

        $post = $this->request->post();

        $item = ProductModel::get($post['id']);

        $result = $item->allowField(true)->save($post, ['id' => $post['id']]);

        if ($result) {
            return zbcjson(true);
        }
        return zbcjson(false, '修改错误', 101);
    }

    public function delete()
    {
        $post = $this->request->post();
        $result  = false;
        $data = $post['data'];

        $result = ProductModel::destroy($data);

        if ($result) {
            return zbcjson(true);
        }
        return zbcjson(false, '删除错误', 101);
    }
}
